from app.models.generate import GenerateBackImage
from app.api.generate.schemas import generate_text_back_image_schema as schema

from app.utils.curd_base import ModelCRUD
from app.utils import security
from app.utils.custom_response import success_response
from fastapi import APIRouter, Query, Body, Path, UploadFile, File, Form
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.system import Users
from typing import Any, Dict, Union, List, Optional
from fastapi.encoders import jsonable_encoder
from app.utils.custom_exc import CustomException
from sqlalchemy import func, or_, not_

from app.utils.file_storage import save_storage_file, get_storage_file, delete_storage_file

router = APIRouter()


class GenerateBackImageCRUD(ModelCRUD):
    model = GenerateBackImage


def get_file_name_type(filename):
    f_type = str(filename).split('.')[-1]
    f_nem = str(filename)[:-len(f_type) - 1]
    return f_nem, f_type


@router.post("/upload_back_image", summary="上传背景图片", response_model=schema.GenerateBackImageSchemaRes,  name='上传背景图片')
async def upload_back_image(
    *,
    db: Session = Depends(get_db),
    file_list: List[UploadFile] = File(...),
    name: str = Form(None, description='名字'),
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    crud = GenerateBackImageCRUD()
    li = []
    for file in file_list:
        dit = {}
        path = save_storage_file(file, folder='generate/backImage')
        dit['path'] = path
        if name:
            dit['name'] = name
        else:
            dit['name'] = get_file_name_type(file.filename)[0]
        item = crud.create(db, data=schema.GenerateBackImageSchemaCreate.validate(dit))
        item_dict = item.to_dict(only=('id', 'name', 'path'))
        item_dict['path'] = get_storage_file(item_dict['path'])
        li.append(item_dict)
    return success_response(data=li)

able_filter_list = [
    {'name': 'name', 'source_filed': 'name', 'lookup_expr': 'ic', 'label': '包含名字', 'type': str, 'method': None, 'required': False},
]


@router.get("/get_back_image", summary="获取背景图片", response_model=schema.GenerateBackImageSchemaRes,  name='获取背景图片')
async def get_back_image(
    request: Request,
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    name: str = Query(None, description='名字'),
    current_user: Users = Depends(security.verify_access_token),
) -> Any:
    crud = GenerateBackImageCRUD()
    order_by_fields = ('-id', )
    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=request.query_params, able_filter_list=able_filter_list, order_by_fields=order_by_fields)
    items = []
    for item in queryset:
        item_dict = item.to_dict(only=('id', 'name', 'path'))
        item_dict['path'] = get_storage_file(item_dict['path'])
        items.append(item_dict)
    resp_data = {
        "items": items,
        'total': total
    }
    return success_response(data=resp_data)


@router.post("/del_back_image", summary="删除背景图片", response_model=schema.GenerateBackImageSchemaRes, name='删除背景图片')
async def del_generate_image(
    *,
    db: Session = Depends(get_db),
    req_data: schema.GenerateBackImageSchemaIDList,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    crud = GenerateBackImageCRUD()
    queryset = crud.get_all_queryset(db)
    req_data = jsonable_encoder(req_data)
    queryset = queryset.filter(crud.model.id.in_(req_data.get('id', [])))
    for instance in queryset:
        delete_storage_file(instance.path)
    queryset.delete()
    db.commit()
    return success_response(data={}, message="删除成功")


@router.post("/update_back_image/{image_id}", summary="更新背景图片", response_model=schema.GenerateBackImageSchemaRes, name='更新背景图片')
async def update_back_image(
    *,
    db: Session = Depends(get_db),
    image_id,
    image_data: schema.GenerateBackImageSchemaUpdate,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    crud = GenerateBackImageCRUD()
    instance = crud.get_object(db, image_id)
    instance = crud.update(db, instance=instance, data=image_data)
    resp_data = instance.to_dict(only=('id', 'name'))
    return success_response(data=resp_data)




